package com.clubs.coding.Service.Impl;

import com.clubs.coding.Service.NewsService;
import com.clubs.coding.exception.ImoocMallException;
import com.clubs.coding.exception.ImoocMallExceptionEnum;
import com.clubs.coding.model.dao.NewsMapper;
import com.clubs.coding.model.pojo.News;
import com.clubs.coding.model.request.NewsReq;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class NewsServiceImpl implements NewsService {
@Autowired
    NewsMapper newsMapper;
@Override
public PageInfo list(Integer pageNum, Integer pageSize, Integer isHome){
    PageHelper.startPage(pageNum, pageSize,"creation_time desc ");
    List<News> newsList = new ArrayList<>();
    if (isHome==1) {
        newsList = newsMapper.selectAllByShowIndexNews();
    }else{
        newsList = newsMapper.selectAll();
    }
    PageInfo pageInfo = new PageInfo(newsList);
    pageInfo.setList(newsList);
   return pageInfo;
}
@Override
public News singleArticle(Integer newsId){
    News news = newsMapper.selectByPrimaryKey(newsId);
    return news;

}
@Override
public void adminbulletin(NewsReq newsReq){
    News news = new News();

    BeanUtils.copyProperties(newsReq,news);
    news.setCreationTime(new Date());
    int i = newsMapper.insertSelective(news);
    if (i==0){
        throw new ImoocMallException(ImoocMallExceptionEnum.INSERT_FAILED);
    }

}
/**
 * 修改文章是否在首页显示
 * **/
@Override
public void adminalter(Integer newsId,Integer show,Integer status){
    News news = new News();
    news.setNewsId(newsId);
    news.setUpdateTime(new Date());
    if (show!=null) {
        news.setShowIndex(show);
    }
    if(status!=null){
        news.setStatus(status);
    }
    newsMapper.updateByPrimaryKeySelective(news);

}

    @Override
    public PageInfo news(Integer pageNum, Integer pageSize, Integer type){
        PageHelper.startPage(pageNum, pageSize,"creation_time desc ");

        List<News> newsList = newsMapper.selectByTypeNews();
        PageInfo pageInfo = new PageInfo(newsList);
        pageInfo.setList(newsList);
        return pageInfo;
    }

    @Override
    public void updatenews(NewsReq newsReq){
        News news = new News();

        BeanUtils.copyProperties(newsReq,news);
        news.setCreationTime(new Date());
        int i = newsMapper.updateByPrimaryKeySelective(news);
        if (i==0){
            throw new ImoocMallException(ImoocMallExceptionEnum.INSERT_FAILED);
        }

    }

}
